<template>
    <common-modal
        ref="modalRef"
        v-bind="attrs"
        @sure="search"
        top="30vh"
        draggable
        @cancel="handleCancel"
        @before-close="reset"
        @open="handleOpen"
    >
        <el-form
            label-width="130px"
            :rules="rules"
            ref="formRef"
            :inline="false"
            :model="formData"
        >
            <el-form-item label="媒体账户：">
                <el-input
                    v-model="account.account"
                    placeholder="请输入媒体账户"
                    disabled
                />
            </el-form-item>
            <el-form-item label="选择文件：" prop="file">
              <el-upload
                class="upload-demo"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :limit="1"
                accept=".xls, .xlsx"
                :http-request="httpRequest"
                :file-list="formData.fileList"
              >
                <el-button type="primary">点击选择文件</el-button>
              </el-upload>
              <a class="template" @click="downloadTemplate" href="javascript:;">点击下载导入模板</a>
            </el-form-item>
        </el-form>
    </common-modal>
</template>
<script>
export default {
    inheritAttrs: false,
};
</script>
<script setup>
import { reactive, useAttrs, ref } from "vue";
import commonModal from "@/components/commonModal.vue";
import useForm from "@/hooks/useForm";
import { ElMessage, ElMessageBox } from "element-plus";
import { importMediaAccount } from '@/apis/media.js'
const accountRef = ref(null)
const props = defineProps({
    id: {
        type: [String, Number],
        default: "",
    },
    account: {
      type: Object,
      default: () => ({})
    }
});
const attrs = useAttrs();
const formData = reactive({
    file: '',
    fileList: []
});
const modalRef = ref(null);
// 确定
const handleSure = async () => {
  await importMediaAccount(props.id, formData.file)
    ElMessage.success({
        message: "操作成功",
        type: "success",
    });
    emits("success");
    handleCancel();
};
const { formRef, search, reset } = useForm(handleSure);

const rules = {
  file: [{ required: true, message: "请选择文件" }],
};

// 取消 关闭弹窗
const handleCancel = () => {
    modalRef.value?.close();
    handleOpen()
};

// 确定
const emits = defineEmits(["success"]);
const beforeRemove = (uploadFile) => {
  return ElMessageBox.confirm(
    `确定删除该文件 ${uploadFile.name} ?`
  ).then(
    () => {
      formData.file = ''
      return true
    },
    () => false
  )
}
const httpRequest = ({ file }) => {
  formData.file = new FormData()
  formData.file.append('file', file)
}
const handleOpen = () => {
  formData.file = ''
  formData.fileList = []
}
const downloadTemplate = () => {
  const { origin, pathname } = window.location
  window.open(`${origin}${pathname}/导入模版.xlsx`)
}
</script>

<style lang="scss" scoped>
.template {
  margin-left: 20px;
}
</style>
